package cl.extractor;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;

import cl.model.dto.Region;
import cl.model.dto.Vehicle;
import cl.util.DataService;

public class VehiclesListExtractor implements ExtractorList{

	public void extract(String  url, String codigoRegion) {
		
		String salidaXML = "";

		HttpClient client = new HttpClient( );
		String query = url;	
		HttpMethod method = new GetMethod( query );

		try {
		    client.executeMethod( method );
		    if( method.getStatusCode( ) == HttpStatus.SC_OK ) {
		        salidaXML = method.getResponseBodyAsString( );
		       // System.out.println( salidaXML );
		    }
		} catch( HttpException he ) {
		    System.out.println( "HTTP Problem: " + he.getMessage( ) );
		} catch( IOException ioe ) {
		    System.out.println( "IO Exeception: " + ioe.getMessage( ) );
		} finally {
		    method.releaseConnection( );
		    method.recycle( );
		}
		
		int tablaPrincipal = salidaXML.indexOf("tbl_Principal");
		ArrayList<Vehicle> idVehiculos = new ArrayList<Vehicle>();; 
		if(tablaPrincipal != -1){

			int indiceTablaPrincipal = tablaPrincipal - 40;
			
			String salidaPrimerCorte = "";
			salidaPrimerCorte=salidaXML.substring(indiceTablaPrincipal);
			
			String[] listadoTR = salidaPrimerCorte.split("</tr>");
			
			Region region = DataService.getInstance().getRegion(codigoRegion);
			
			for(int i = 0 ;i<listadoTR.length;i++){
				
				if(listadoTR[i]!=null && listadoTR[i].indexOf("auto.asp")!=-1){
					
					int href = listadoTR[i].indexOf("href");
					int onmouseover = listadoTR[i].indexOf("onmouseover");
					Vehicle vehicle = new Vehicle();
					vehicle.setCodigoVehiculo(listadoTR[i].substring(href+6,onmouseover-3).replace("auto.asp?codauto=", ""));
					
					//idVehiculos.add(listadoTR[i].substring(href+6,onmouseover-3).replace("auto.asp?codauto=", ""));
					//idVehiculos.add(vehicle);
					addVehicle(listadoTR[i].substring(href+6,onmouseover-3).replace("auto.asp?codauto=", ""),region);				
				}
			}
			//System.out.println("Vehiculos encontrados : " + idVehiculos.size());
		}
		else{
		System.out.println("ERROR : No se encontraron Vehiculos");
		}
	}

	private void addVehicle(String codigoVehicle, Region region) {
		Vehicle vehicle = DataService.getInstance().crearVehicle("","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","","",codigoVehicle,region);
		System.out.println(vehicle.getRegion().getCodigoRegion());
	}

}
